package com.kyrioscraft.cloud.thead.jdklab.tools.pool;

import java.util.concurrent.*;

/**
 * @Author kyrioscraft
 * @Date 2019/2/19 11:21
 * @Description
 * 线程拒绝策略，ThreadPoolExecutor的内部类实现了四种拒绝策略CallerRunsPolicy，AbortPolicy，DiscardPolicy，DiscardOldestPolicy，
 * 也可以自己实现RejectedExecutionHandler接口自定义拒绝策略
 *
 * 线程自定义创建工厂 可以通过默认Executors.defaultThreadFactory()方式提供工厂，也可以自定义线程创建
 **/
public class RejectThreadPoolDemo {
    public static class MyTask implements Runnable {

        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + ":Thread ID:" + Thread.currentThread().getId());

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyTask task = new MyTask();
        ExecutorService es = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(10),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setPriority(9);
                        System.out.println("create " + t);
                        return t;
                    }
                },

                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println(r.toString() + "is discard");
                    }
                });
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            es.submit(task);
            Thread.sleep(10);
        }
    }
}
